// ws-server.js
const WebSocket = require('ws');
const PORT = 80; // WebSocket 服务器端口

const wss = new WebSocket.Server({ port: PORT });

// 存储所有连接的客户端
const clients = new Map(); // 使用Map来存储用户ID和WebSocket连接的映射

wss.on('connection', (ws, req) => {
  // 从URL中获取用户ID
  const url = new URL(req.url, 'ws://localhost');
  const userId = url.searchParams.get('userId');
  
  if (userId) {
    clients.set(userId, ws);
    console.log(`用户 ${userId} 已连接，当前连接数: ${clients.size}`);
  }

  // 消息中转逻辑
  ws.on('message', (data) => {
    try {
      // 确保数据是字符串格式
      const messageStr = data.toString();
      const message = JSON.parse(messageStr);
      console.log(`收到消息:`, message);
    
      // 如果消息包含接收者ID，只发送给特定用户
      if (message.receiverId && clients.has(message.receiverId)) {
        const receiverWs = clients.get(message.receiverId);
        if (receiverWs.readyState === WebSocket.OPEN) {
          // 确保发送的是字符串
          receiverWs.send(messageStr);
      }
      }
    } catch (error) {
      console.error('消息处理错误:', error);
    }
  });

  ws.on('close', () => {
    // 找到并删除断开连接的用户
    for (const [id, client] of clients.entries()) {
      if (client === ws) {
        clients.delete(id);
        console.log(`用户 ${id} 断开连接，剩余连接数: ${clients.size}`);
        break;
      }
    }
  });
});

console.log(`WebSocket 服务器运行在 ws://localhost:${PORT}`);